﻿using JinYuan.Helper;
using JinYuan.Models;
using JinYuan.VirtualDataLibrary;
using Language;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace LargeSquareOne
{
    public partial class FrmImgDisplay : MultiLanguageForm
    {
        public static FrmImgDisplay _Form;// 单例模式

        private List<PictureBox> _pictureBoxList = new List<PictureBox>();
        private float _zoomFactor = 1.0f; // 缩放因子，
        private const float _zoomStep = 0.1f; // 缩放的步长
        private Point _lastMousePos; // 记录鼠标上次位置，用于拖动
        private bool _isDragging = false; // 是否正在拖动图片
        public FrmImgDisplay()
        {
            InitializeComponent();

           
            this.cmb_SelectType.Items.AddRange(new string[] { "NG", "OK" });
            this.cmb_SelectType.SelectedIndex = 0;

            this.dtp_Start.Value = DateTime.Now.AddHours(-2.0f);


            // 本地图片
            //pictureBox.Image = Image.FromFile("a.jpg");
            //LoadWebImage(this.pictureBox1, "http://192.168.133.180:8055/2025-08-30/ng/a_");
           
            this.DoubleBuffered = true;


            this.pictureBox1.MouseWheel += PictureBox_MouseWheel;
            this.pictureBox1.MouseDown += PictureBox_MouseDown;
            this.pictureBox1.MouseMove += PictureBox_MouseMove;
            this.pictureBox1.MouseUp += PictureBox_MouseUp;

            this.panel5.AutoScroll = true; 

            _Form = this;
        }
        /// <summary>
        /// 查询IMG
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_QueryImg_Click(object sender, EventArgs e)
        {
            
            ClearAllPictureBoxes(panel6);           
            //查询
            string str = this.cmb_SelectType.Text;
            if (string.Compare(str, "NG") == 0)
            {
                this.cmb_SelectType.SelectedIndex = 0;
            }
            else if (string.Compare(str, "OK") == 0)
            {
                this.cmb_SelectType.SelectedIndex = 1;
            }
           
            string barCode = this.txtSteelShellCode.Text.Trim();
            string start = this.dtp_Start.Text;
            // 2. 创建PictureBox并添加到Panel
            var listImg = LoadWebImage(null, $"{CommonMethods.mesConfig.ImgServerIP}/{start}/{str}/{barCode}_");
            if (listImg.Count > 0)
            {
                for (int i = 0; i < listImg.Count; i++)
                {

                    PictureBox pictureBox = new PictureBox
                    {
                        SizeMode = PictureBoxSizeMode.Zoom,
                        Size = new Size(230, 174),
                        BorderStyle = BorderStyle.FixedSingle,
                        Location = new Point(0, (174 + 10) * i)
                    };

                    pictureBox.Click += PictureBox_Click;
                    panel6.Controls.Add(pictureBox);
                    _pictureBoxList.Add(pictureBox);
                    DisplayImg(pictureBox, listImg[i]);
                }
            }
            else
            {
                MessageBox.Show($"No Picture in{start}/{str}/{barCode}");
            }
        }
        private void ClearAllPictureBoxes(Panel panel)
        {
            if (panel.InvokeRequired)
            {
                panel.Invoke(new Action<Panel>(ClearAllPictureBoxes), panel);
                return;
            }

            try
            {
                panel.SuspendLayout();
                panel.Visible = false; 

                foreach (var pb in _pictureBoxList)
                {
                    if (pb == null || pb.IsDisposed) continue;
                    pb.Click -= PictureBox_Click;

                    pb.SizeMode = PictureBoxSizeMode.Normal;
                    pb.Image = null; 

                    if (pb.Image != null)
                    {
                        pb.Image.Dispose();
                        pb.Image = null;
                    }

                    if (!panel.Controls.Contains(pb)) continue; 
                    panel.Controls.Remove(pb);

                    pb.Invalidate();
                    pb.Update();
                    pb.Dispose();
                }

                _pictureBoxList.Clear();
                panel.Controls.Clear(); 

                pictureBox1.Image = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error：{ex.Message}\n{ex.StackTrace}", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                panel.Visible = true;
                panel.ResumeLayout(true);
                panel.Invalidate(); 
            }
        }
        /// <summary>
        /// 加载网络图片
        /// </summary>
        /// <param name="pictureBox"></param>
        /// <param name="imageUrl"></param>
        private List<Image> LoadWebImage(PictureBox pictureBox, string imageUrl, int startIndex = 0)
        {
            List<Image> listImg = new List<Image>();
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    byte[] imageBytes = null;
                    do
                    {
                        imageBytes = webClient.DownloadData($"{imageUrl}{startIndex}.jpg");                        
                        if (imageBytes != null && imageBytes.Length > 0)
                        {
                            startIndex++;
                            using (var stream = new System.IO.MemoryStream(imageBytes))
                            {
                                Image image = Image.FromStream(stream);
                                listImg.Add(image);                                
                                if (pictureBox != null)
                                {
                                    DisplayImg(this.pictureBox1, image);
                                }
                            }
                        }
                    }
                    while (imageBytes != null && imageBytes.Length > 0);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError($"加载图片失败：{imageUrl}{startIndex}.jpg");
            }
            return listImg;
        }

        // 缩放图片
        private void PictureBox_MouseWheel(object sender, MouseEventArgs e)
        {

            if (sender is not PictureBox pictureBox || pictureBox.Image == null)
                return;

            Panel panel = pictureBox.Parent as Panel;
            if (panel == null) return;

            Point mouseInPanel = e.Location; 
                                            
            mouseInPanel.Offset(pictureBox.Location);

            float mouseXRatio = (float)e.X / pictureBox.Width;  
            float mouseYRatio = (float)e.Y / pictureBox.Height; 

           
            int oldWidth = pictureBox.Width;
            int oldHeight = pictureBox.Height;
            int oldScrollX = -panel.AutoScrollPosition.X;
            int oldScrollY = -panel.AutoScrollPosition.Y;

            if (e.Delta > 0)
                _zoomFactor = Math.Min(_zoomFactor + _zoomStep, 5.0f); 
            else
                _zoomFactor = Math.Max(_zoomFactor - _zoomStep, 0.1f); 

            int newWidth = (int)(pictureBox.Image.Width * _zoomFactor);
            int newHeight = (int)(pictureBox.Image.Height * _zoomFactor);
            pictureBox.Size = new Size(newWidth, newHeight);

            int newScrollX = (int)(mouseXRatio * newWidth) - mouseInPanel.X;
            int newScrollY = (int)(mouseYRatio * newHeight) - mouseInPanel.Y;

            newScrollX = Math.Max(0, Math.Min(newScrollX, Math.Max(0, newWidth - panel.ClientSize.Width)));
            newScrollY = Math.Max(0, Math.Min(newScrollY, Math.Max(0, newHeight - panel.ClientSize.Height)));

            panel.AutoScrollPosition = new Point(newScrollX, newScrollY);
        }
       
        private void PictureBox_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isDragging && sender is PictureBox pictureBox && pictureBox.Parent is Panel panel)
            {
                Point screenMousePos = Control.MousePosition;

                Point panelMousePos = panel.PointToClient(screenMousePos);

                int deltaX = _lastMousePos.X - screenMousePos.X;
                int deltaY = _lastMousePos.Y - screenMousePos.Y;

                int currentScrollX = -panel.AutoScrollPosition.X;
                int currentScrollY = -panel.AutoScrollPosition.Y;

                int newScrollX = currentScrollX - deltaX; 
                int newScrollY = currentScrollY - deltaY;

             
                newScrollX = Math.Max(0, Math.Min(newScrollX, Math.Max(0, pictureBox.Width - panel.ClientSize.Width)));
                newScrollY = Math.Max(0, Math.Min(newScrollY, Math.Max(0, pictureBox.Height - panel.ClientSize.Height)));

                panel.AutoScrollPosition = new Point(newScrollX, newScrollY);

                _lastMousePos = screenMousePos;
            }
        }

        // MouseDown事件
        private void PictureBox_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && sender is PictureBox pictureBox)
            {
                _lastMousePos = Control.MousePosition;
                _isDragging = true;
                pictureBox.Cursor = Cursors.SizeAll;
            }
        }

        // 鼠标释放
        private void PictureBox_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _isDragging = false;
                panel5.ResumeLayout(true);
                ((PictureBox)sender).Cursor = Cursors.Hand;
            }
        }
        /// <summary>
        /// 图片点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PictureBox_Click(object sender, EventArgs e)
        {
            var image = ((PictureBox)sender).Image;
            DisplayImg(this.pictureBox1, image);
        }
        /// <summary>
        /// picturebox 显示图片
        /// </summary>
        /// <param name="pictureBox"></param>
        /// <param name="image"></param>
        private void DisplayImg(PictureBox pictureBox, Image image)
        {
            if (pictureBox.InvokeRequired)
            {
                pictureBox.Invoke(new Action(() =>
                {
                    pictureBox.Image = image;
                }));
            }
            else
            {
                pictureBox.Image = image;
            }
        }

        #region 减少闪烁
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams parss = base.CreateParams;
                parss.ExStyle |= 0x02000000;
                return parss;
            }
        }
        #endregion
    }
}
